package com.huluwa.jczq.util;


import com.alibaba.fastjson.JSONPath;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.huluwa.jczq.common.Constant.yaosenBetSelector;

public class Parser {
    private final static Logger logger = LoggerFactory.getLogger(Parser.class);

    /**
     * 投注/重发/主动通知报文(XML格式)解析
     * XML格式
     * @param ticketId ：合作方票号;
     * @param selector ：根据票号定位具体的xml节点;
     * @param originMsg ：grep得到的原始的报文信息
     * @return  返回该票号的报文，若解析失败，返回错误信息
     */
    public String getXMLMsgByTicketId(String ticketId,String selector,String originMsg)  {
        //String key = "【http send】";
        String msg = null;
        //String getMessageXml = originMsg.substring(originMsg.indexOf(key)+key.length());

        Document doc = null;
        try {
            doc = DocumentHelper.parseText(originMsg);
        } catch (DocumentException e) {
            logger.error("原始报文转化xml失败,originMsg - {}",originMsg,e);
            msg = "报文解析xml失败,ticketId:"+ticketId;
            return msg;
        }
        try{
            selector = selector.replace("{ticketId}",ticketId);
            msg = doc.selectSingleNode(selector).asXML();
        } catch (Exception e){
            msg = "该票号信息不存在,ticketId:"+ticketId;
            logger.info("ticketId - {},selector - {}",ticketId,selector);
            logger.error("该票号信息未解析到,originMsg - {}",originMsg,e);
        }
        return  msg;
    }

    /**
     *  解析json类型的报文
     * @param ticketId
     * @param selector
     * @param originMsg
     * @return
     */
    public String getJsonMsgByTicketId(String ticketId,String selector,String originMsg){
        String jsonStr = originMsg.replace("{ticketId}",ticketId);
        String msg = "";
        try{
            msg = (String) JSONPath.read(jsonStr, selector);
        }catch (Exception e){
            logger.error("原始报文转化xml失败,originMsg - {}",originMsg,e);
            msg = "报文解析xml失败,ticketId:"+ticketId;
            return msg;
        }
        if(msg == "" || msg == null){
            msg = "该票号信息不存在,ticketId:"+ticketId;
            logger.info("ticketId - {},selector - {}",ticketId,selector);
            logger.error("该票号信息未解析到,originMsg - {}",originMsg);
        }
        return msg;
    }

    /**
     * 正则解析
     * @param ticketId
     * @param selector
     * @param originMsg
     * @return
     */
    public String getStrMsgByTicketId(String ticketId,String selector,String originMsg){
        String str = originMsg.replace("{ticketId}",ticketId);
        String msg = "";
        try{
            // 编译正则表达式
            Pattern pattern = Pattern.compile(selector);
            // 忽略大小写的写法
            // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(str);
            // 字符串是否与正则表达式相匹配
            boolean rs = matcher.matches();
            msg = matcher.group(1);
            //System.out.println(msg);
        }catch (Exception e){
            logger.error("原始报文转化失败,originMsg - {}",originMsg,e);
            msg = "报文解析失败,ticketId:"+ticketId;
            return msg;
        }
        if(msg == "" || msg == null){
            msg = "该票号信息不存在,ticketId:"+ticketId;
            logger.info("ticketId - {},selector - {}",ticketId,selector);
            logger.error("该票号信息未解析到,originMsg - {}",originMsg);
        }
        return msg;
    }
    public static void main(String[] argv){
        Parser xmlParser = new Parser();
        String getMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "\n" +
                "<body> \n" +
                "  <tickets> \n" +
                "    <ticket> \n" +
                "      <ordersID>商户订单号</ordersID>  \n" +
                "      <ticketId>票号(彩票落地号)</ticketId>  \n" +
                "      <status>状态</status>  \n" +
                "      <printTime>时间</printTime>  \n" +
                "      <odds>赔率</odds> \n" +
                "    </ticket>  \n" +
                "    <ticket> \n" +
                "      <ordersID>商户订单号1</ordersID>  \n" +
                "      <ticketId>票号(彩票落地号)</ticketId>  \n" +
                "      <status>状态</status>  \n" +
                "      <printTime>时间</printTime>  \n" +
                "      <odds>赔率</odds> \n" +
                "    </ticket> \n" +
                "  </tickets> \n" +
                "</body>\n";
        String ticketInfo = xmlParser.getJsonMsgByTicketId("商户订单号",yaosenBetSelector,getMessage);
        System.out.println(ticketInfo);
        logger.info("msg:{}",ticketInfo);
    }

}
